<template>
  <div :class="isBack ? 'order-detail' : 'order-box'">
    <div :class="isBack ? 'order-content' : 'order-content content-width'">
      <OrderTitleBar title="订单详情"
                     :value="order"
                     :is-all="all"
                     :is-back="isBack"
                     @sign="signDialogVisible = true"
                     @receipt="receiptDialogVisible = true" />
      <div style="padding: 20px 20px 0px">
        <OrderDescriptions :value="order" />
      </div>
      <div style="padding: 0 20px"><el-divider /></div>
      <el-row :gutter="40">
        <el-col :span="12">
          <OrderCustomer :value="order" />
        </el-col>
        <el-col :span="12">
          <OrderConsignee :value="order" />
        </el-col>
      </el-row>
      <SimpleTab title="货物信息">
        <OrderGoodsList :value="order"
                        :is-all="all"
                        @input="handleGoodsListInput" />
      </SimpleTab>
      <SimpleTab v-if="showReceiptPics"
                 title="其它信息">
        <el-row class="info_sty">
          <el-col :span="2"
                  class="label-sty">签收时间</el-col>
          <el-col :span="20"
                  class="value-sty">
            {{order.signTime}}
          </el-col>
        </el-row>
        <el-row class="info_sty">
          <el-col :span="2"
                  class="label-sty">延期原因</el-col>
          <el-col :span="20"
                  class="value-sty">
            {{(order.receipt && order.receipt.delayReasonName) || (order.sign && order.sign.delayReasonName) || '--'}}
          </el-col>
        </el-row>
        <el-row class="info_sty">
          <el-col :span="2"
                  class="label-sty">签收照片</el-col>
          <el-col :span="20">
            <attachments v-if="signPicsArr.length"
                         :value="signPicsArr" />
            <span v-else>--</span>
          </el-col>
        </el-row>
        <el-row v-if="refusePicsArr.length"
                class="info_sty">
          <el-col :span="2"
                  class="label-sty">拒签照片</el-col>
          <el-col :span="20">
            <attachments :value="refusePicsArr" />
          </el-col>
        </el-row>
        <el-row v-if="isCompleted"
                class="info_sty">
          <el-col :span="2"
                  class="label-sty">回单照片</el-col>
          <el-col :span="20">
            <attachments v-if="receiptPicsArr.length"
                         :value="receiptPicsArr" />
            <span v-else>--</span>
          </el-col>
        </el-row>
      </SimpleTab>
      <SimpleTab title="运输信息">
        <OrderArguments :value="order" />
        <OrderAttachments :value="order" />
      </SimpleTab>
      <SimpleTab v-if="showScore && order.score"
                 title="签收评价">
        <OrderSignScore :value="order.score.star"
                        :score-label-desc="scoreLabelDesc"
                        :score-desc="order.score.remarks" />
      </SimpleTab>
      <OrderSignSubmit :value="order"
                       :visible.sync="signDialogVisible"
                       :before-submit="handleSignSubmitBefore"
                       :is-all="all"
                       :goods-list="goodsList"
                       :loading.sync="loading"
                       @submit="handleSignSubmit" />
      <OrderReceiptSubmit :value="order"
                          :visible.sync="receiptDialogVisible"
                          :before-submit="handleReceiptSubmitBefore"
                          :goods-list="goodsList"
                          :loading.sync="loading"
                          @submit="handleReceiptSubmitConfirm" />
      <SimpleTab v-show="isTrack"
                 title="跟踪信息">
        <Information :value="track" />
      </SimpleTab>
    </div>
  </div>
</template>

<script>
import _ from "lodash";
import { order, track } from "@/api/index";
// import OrderReceiptPics from "@/components/order/OrderReceiptPics";
import OrderTitleBar from "@/components/order/OrderTitleBar";
import OrderDescriptions from "@/components/order/OrderDescriptions";
import OrderConsignee from "@/components/order/OrderConsignee";
import OrderCustomer from "@/components/order/OrderCustomer";
import OrderGoodsList from "@/components/order/OrderGoodsList";
import OrderArguments from "@/components/order/OrderArguments";
import OrderAttachments from "@/components/order/OrderAttachments";
import OrderReceiptSubmit from "@/components/order/OrderReceiptSubmit";
import OrderSignSubmit from "@/components/order/OrderSignSubmit";
import OrderSignScore from "@/components/order/OrderSignScore";
import SimpleTab from "@/components/basic/SimpleTab.vue";
import Information from "@/components/track/Information.vue";
import { STATUS_CODES, ATTACHMENT_TYPES } from "./order.mixin";
// import OrderDesc from "@/components/order/OrderDesc";
// import OrderSignPics from "@/components/order/OrderSignPics";
import { returnCompareTime } from "@/libs/util.js";
import Attachments from "@basic/Attachments.vue";

export default {
  name: "OrderDetails",
  components: {
    SimpleTab,
    OrderTitleBar,
    OrderDescriptions,
    OrderCustomer,
    OrderConsignee,
    OrderGoodsList,
    OrderArguments,
    OrderAttachments,
    OrderReceiptSubmit,
    OrderSignSubmit,
    OrderSignScore,
    Information,
    // OrderDesc,
    // OrderSignPics,
    Attachments
  },
  data () {
    return {
      order: {},
      goodsList: [],
      receiptPics: [],
      receiptDialogVisible: false,
      signDialogVisible: false,
      loading: false,
      track: [], // 跟踪信息
      isTrack: false, // 跟踪信息标题显示
      descOption: "", // 备注选项
      signPicsArr: [],
      refusePicsArr: [],
      receiptPicsArr: [],
      isBack: true,
    };
  },
  computed: {
    orderId () {
      return Number(this.$route.query?.orderId || this.$route.query?.id);
    },
    showReceiptPics () {
      return (
        this.order.status === STATUS_CODES.WAIT_RECEIPT ||
        this.order.status === STATUS_CODES.COMPLETED
      );
    },
    showSigsPics () {
      return (
        this.order.status === STATUS_CODES.WAIT_SIGN ||
        this.order.status === STATUS_CODES.WAIT_RECEIPT ||
        this.order.status === STATUS_CODES.COMPLETED
      );
    },
    signPics () {
      return this.order.status === STATUS_CODES.WAIT_SIGN
    },
    showScore () {
      return [30, 40].includes(this.order.status) && this.order?.score;
    },
    hasSignNumOver () {
      return this.goodsList.filter((goods) => goods.isSignNumOver).length > 0;
    },
    hasSignNumLack () {
      return this.goodsList.filter((goods) => goods.isSignNumLack).length > 0;
    },
    hasSignNumZero () {
      return this.goodsList.filter((goods) => goods.isSignNumZero).length > 0;
    },
    scoreLabelDesc () {
      let desc = this.order?.score?.labels?.toString()
      return desc ? desc.replace(',', '，') : null
    },
    isCompleted () {
      return this.order.status === STATUS_CODES.COMPLETED || this.receiptPicsArr.length;
    },
    all () {
      // 是否为全部列表进入
      const { name } = this.$route
      return name === 'orderDetailsWindow';
    }
  },
  created () {
    this.loadOrder();
    this.trackInformation();
  },
  // 页面销毁之前
  beforeDestroy () {
    sessionStorage.removeItem('PARAMS_DATA')
  },
  methods: {
    async loadOrder () {
      let { code, data = {} } = await order.orderDetailsApi(this.orderId);
      if (0 === code) {
        this.order = data;
        if (data.signDesc && data.signDesc.includes('【') && data.signDesc.includes('】')) {
          this.descOption = data.signDesc.slice(data.signDesc.indexOf('【') + 1, data.signDesc.indexOf('】'));
        }
      }
      if (this.all || ![20, 30].includes(data?.status)) {
        this.isBack = false;
      }
      if (data?.sign?.attachments && data?.sign?.attachments.length) {
        this.signPicsArr = data?.sign?.attachments?.filter(
          (attachment) => attachment.type === ATTACHMENT_TYPES.SIGN_PIC || attachment.type === ATTACHMENT_TYPES.SIGN_QRCODE_PIC
        );
        this.refusePicsArr = data?.sign?.attachments?.filter(
          (attachment) => attachment.type === ATTACHMENT_TYPES.REJECT_SIGN_PIC
        );
      }
      if (data?.receipt?.attachments && data?.receipt?.attachments.length) {
        this.receiptPicsArr = data?.receipt?.attachments?.filter(
          (attachment) => attachment.type === ATTACHMENT_TYPES.RECEIPT_PIC || attachment.type === ATTACHMENT_TYPES.RECEIPT_SYNC
        );
        let refusePics = data?.receipt?.attachments?.filter(
          (attachment) => attachment.type === ATTACHMENT_TYPES.REJECT_RECEIPT_PIC
        );
        this.refusePicsArr = [...this.refusePicsArr, ...refusePics];
      }
    },
    closeWindowWait () {
      this.$router.back();
      // window.close();
    },
    handleGoodsListInput (goodsList) {
      this.goodsList = goodsList;
    },
    handleReceiptPicsInput (receiptPics) {
      this.receiptPics = receiptPics;
    },
    handleSignPicsInput (signPics) {
      this.receiptPics = signPics;
    },
    OrderDescOption (descOption) {
      this.descOption = descOption;
    },
    handleReceiptSubmitBefore ({ receiptSignTime, receiptTime }) {
      if (!receiptTime) {
        this.$message({ type: "error", message: "回单时间不能为空" });
        return false;
      }
      if (receiptSignTime) {
        if (receiptTime && returnCompareTime(
          new Date(this.$moment(receiptSignTime).format("YYYY-MM-DD HH:mm:ss")),
          new Date(this.$moment(receiptTime).format("YYYY-MM-DD HH:mm:ss"))
        )) {
          this.$message({ type: "error", message: "回单时间不能早于签收时间" });
          return false;
        }
      } else {
        if (receiptTime && returnCompareTime(
          new Date(this.$moment(this.order.signTime).format("YYYY-MM-DD HH:mm:ss")),
          new Date(this.$moment(receiptTime).format("YYYY-MM-DD HH:mm:ss"))
        )) {
          this.$message({ type: "error", message: "回单时间不能早于签收时间" });
          return false;
        }
      }
      return true;
    },
    async handleReceiptConfirm (receipt) {
      // 订单照片为空二次确认框
      this.$confirm('回单照片为空，是否继续', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        this.handleReceiptSubmit(receipt)
      })
    },
    async handleReceiptSubmitConfirm (receipt) {
      if (receipt?.receiptPics.length === 0) {
        return this.handleReceiptConfirm(receipt)
      }
      this.handleReceiptSubmit(receipt)
    },
    async handleReceiptSubmit (receipt) {
      this.loading = true;
      const { orderId } = this.order;
      const { receiptType: exception, receiptDesc: remarks, receiptTime, receiptSignTime, delayReason, receiptPics, receiptRefusePics } = receipt;

      receiptPics.length && receiptPics.map(item => {
        item.type = ATTACHMENT_TYPES.RECEIPT_PIC;
      })
      receiptRefusePics.length && receiptRefusePics.map(item => {
        item.type = ATTACHMENT_TYPES.REJECT_RECEIPT_PIC;
      })

      // 接口中quantity表示签收数量
      const receiptGoodsList = _.cloneDeep(this.goodsList);
      receiptGoodsList.forEach((goods) => {
        goods.quantity = goods.signQuantity;
        goods.remarks = goods.exceptionDesc;
        delete goods.goodsSign;
      });

      const { code, message } = await order.receipt({
        orderId,
        attachments: [...receiptRefusePics, ...receiptPics],
        receiptTime,
        receiptSignTime,
        exception,
        delayReason,
        remarks,
        receipts: receiptGoodsList
      })
        .catch(() => {
          this.loading = false;
        });
      if (0 === code) {
        this.loading = false;
        this.$message({ type: "success", message });
        this.receiptDialogVisible = false;
        this.closeWindowWait();
      }
    },
    handleSignSubmitBefore () {
      return true;
    },
    // handleSignConfirm (sign) {
    //   // 订单照片为空二次确认框
    //   this.$confirm('签收照片为空，是否继续', '提示', {
    //     confirmButtonText: '确定',
    //     cancelButtonText: '取消',
    //     type: 'warning'
    //   }).then(async () => {
    //     this.handleSignSubmit(sign)
    //   })
    // },
    // handleSignSubmitConfirm (sign) {
    //   if (sign?.signPics?.length === 0) {
    //     return this.handleSignConfirm(sign)
    //   }
    //   this.handleSignSubmit(sign)
    // },
    async handleSignSubmit (sign) {
      if (this.hasSignNumOver) {
        this.$message.warning("实签数量不能大于物品数量！");
        return;
      }

      if (this.hasSignNumLack) {
        this.$message.warning("实签数量+异常数量不能小于物品数量！");
        return;
      }

      if (this.hasSignNumZero) {
        this.$message.warning("实签数量不能为空！");
        return;
      }

      // 接口中quantity表示签收数量
      const signs = _.cloneDeep(this.goodsList);
      signs.forEach((goods) => {
        goods.quantity = goods.signQuantity;
        goods.remarks = goods.exceptionDesc;
      });
      // 签收照片
      const signPics = sign.signPics;
      signPics.length && signPics.map(item => {
        item.type = ATTACHMENT_TYPES.SIGN_PIC;
      })
      // 拒签照片
      const signRefusePics = sign.signRefusePics;
      signRefusePics.length && signRefusePics.map(item => {
        item.type = ATTACHMENT_TYPES.REJECT_SIGN_PIC;
      })

      if ([1, 3].includes(this.order?.trackType) && [1, 2].includes(this.order?.transportStatus)) {
        return this.$confirm("订单没到目的地，确认签收吗？", "提示", {
          confirmButtonText: "确认",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.loading = true;
          this.sign(sign, signPics, signRefusePics, signs);
        });
      } else {
        this.loading = true;
        this.sign(sign, signPics, signRefusePics, signs);
      }
    },
    async sign (sign, signPics, signRefusePics, signs) {
      console.log("========>sign", signs)
      const response = await order.sign({
        attachments: sign.exception ? [...signPics, ...signRefusePics] : signPics,
        orderId: this.orderId,
        signType: 0, //签收类型：平台签收
        remarks: sign.signDesc, // 签收说明
        delayReason: sign.delayReason,
        signs
      })
        .catch(() => {
          this.loading = false;
        });
      if (response?.code === 0) {
        this.loading = false;
        this.$message({ type: "success", message: "签收成功" });
        this.signDialogVisible = false;
        this.closeWindowWait();
      }
    },
    // 跟踪信息
    async trackInformation () {
      let type = 'order'
      let { code, data } = await track.information(this.orderId, type);
      if (code === 0 && data.length) {
        data.map(item => {
          if (item.message.indexOf('，') != -1 && item.message.lastIndexOf('】')) {
            item.timestamp = item.message.slice(0, item.message.indexOf('，'))
            item.date = item.message.slice(item.message.indexOf('，') + 1, item.message.lastIndexOf('】') + 1)
            item.content = item.message.slice(item.message.lastIndexOf('】') + 1)
          }
        })
        this.track = data
        this.isTrack = true
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.order-box {
  width: 100%;
  height: calc(100vh);
  overflow-x: hidden;
  overflow-y: scroll;
}
.order-detail {
  width: 100%;
  height: calc(100vh - 80px);
  overflow-x: hidden;
  overflow-y: scroll;
}
.order-content {
  margin: 0 auto;
  background: var(--prev-bg-white);
  min-height: 100vh;
}
.content-width {
  width: 1200px;
}
.info_sty {
  line-height: 30px;
  margin-bottom: 10px;
}
.label-sty {
  font-size: 16px;
  color: var(--prev-color-text-primary);
}
.value-sty {
  font-size: 16px;
  color: var(--prev-color-text-primary);
  font-weight: bold;
}
</style>